<script setup lang="ts">
import { onUnmounted, ref } from "vue"
import { Output, compile, runBf } from "./js/"

const src = ref('+[-->-[>>+>-----<<]<--<---]>-.>>>+.>>..+++[.>]<<<<.+++.------.<<-.>>>>+.')
const opt = ref(true)
const log = ref('')
const code = ref(compile('', false) as Output)

const input = ref('')
const size = ref(1)
const pos = ref(10)
const output = ref('')
const state = ref('')
const kill = ref(() => { })

const toCompile = () => {
    const res = compile(src.value, opt.value)
    if (typeof res == 'string') {
        log.value = res
    } else {
        log.value = 'Complete'
        code.value = res
    }
}

const stop = () => {
    output.value = ''
    kill.value()
    state.value = 'Stopped'
}

const run = async () => {
    stop()
    state.value = 'Running'
    const inp = [...input.value].map(c => c.charCodeAt(0))
    kill.value = runBf(
        await code.value.wasm,
        inp,
        pos.value,
        size.value,
        out => { output.value = out },
        () => { state.value = 'Complete' },
        msg => { state.value = 'Error: ' + msg },
    )
}

onUnmounted(() => kill.value())

</script>

<template>
    Source Code: <br>
    <textarea v-model="src"></textarea><br>
    Optimize: <input type="checkbox" v-model="opt"><br>
    <button v-on:click="toCompile">Compile</button> {{ log }}<br>
    <hr>
    IR: <br>
    <textarea readonly>{{ code.ir }}</textarea><br>
    C: <br>
    <textarea readonly>{{ code.c }}</textarea><br>
    <hr>
    Input: <br>
    <textarea v-model="input"></textarea><br>
    Size: <input v-model="size"><br>
    Position: <input v-model="pos"><br>
    <button v-on:click="run">Run</button> <button v-on:click="stop">Stop</button>
    {{ state }}<br>
    Output: <br>
    <textarea readonly>{{ output }}</textarea><br>
</template>

<style scoped></style>
